package logic

import (
	"context"
	"fmt"
	"io"
	"net/http"

	"goNutpi/internal/svc"
	"goNutpi/internal/types"

	"github.com/tidwall/gjson"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest/httpc"
)

type LessonListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLessonListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LessonListLogic {
	return &LessonListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LessonListLogic) LessonList(req *types.LessonListReq) (resp *types.LessonListResp, err error) {
	// todo: add your logic here and delete this line
	url := "https://tiger-api.helloworld.net/v1/lesson/list/all?" +
		fmt.Sprintf("pageNum=%d&pageSize=%d&directionId=%d&categoryId=%d&level=%d&type=%d",
			req.PageNum, req.PageSize, req.DirectionId, req.CategoryId, req.Level, req.Type)

	res, err := httpc.Do(l.ctx, http.MethodGet, url, nil)
	if err != nil {
		l.Errorf("Failed to make HTTP request: %v", err)
		return nil, err
	}
	defer res.Body.Close()

	body, err := io.ReadAll(res.Body)
	if err != nil {
		l.Errorf("Failed to read response body: %v", err)
		return nil, err
	}

	// 检查HTTP状态码
	if res.StatusCode != http.StatusOK {
		l.Errorf("Unexpected status code: %d", res.StatusCode)
		return nil, fmt.Errorf("unexpected status code: %d", res.StatusCode)
	}

	// 解析JSON数据
	jsonResult := gjson.ParseBytes(body)

	// 检查API返回的code
	if jsonResult.Get("code").Int() != 1 {
		l.Errorf("API returned non-1 code: %d", jsonResult.Get("code").Int())
		return nil, fmt.Errorf("API returned non-1 code: %d", jsonResult.Get("code").Int())
	}

	// 构造返回的数据结构
	resp = &types.LessonListResp{
		Code:    int(jsonResult.Get("code").Int()),
		Message: jsonResult.Get("message").String(),
		Data: types.DataItem{
			Total: int(jsonResult.Get("data.total").Int()),
		},
	}

	// 解析list数组
	rows := jsonResult.Get("data.list").Array()
	for _, row := range rows {
		lesson := types.Lesson{
			Cover:          row.Get("cover").String(),
			DiscountAmount: int(row.Get("discountAmount").Int()),
			Mark:           int(row.Get("mark").Int()),
			Name:           row.Get("name").String(),
			PayCount:       int(row.Get("payCount").Int()),
			Price:          int(row.Get("price").Int()),
			Status:         int(row.Get("status").Int()),
			UUID:           row.Get("uuid").String(),
		}
		resp.Data.List = append(resp.Data.List, lesson)
	}

	return resp, nil
}
